﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DotNetNuke;
using DotNetNuke.Application;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Security;
using DotNetNuke.Services.Installer;
using DotNetNuke.Services.Installer.Packages;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Modules;
using DotNetNuke.UI.WebControls;

namespace CharityGamesOnline.Modules.Game
{
    public partial class Extensions : ModuleUserControlBase, IActionable
    {
        private string _Mode = "Module";
        public string PackageType
        {
            get { return "Module"; }
        }
        public string Mode
        {
            get
            {
                return _Mode;
            }
        }
        protected string GetIsPackageInUseInfo(object dataItem)
        {
            if ((dataItem is PackageInfo))
            {
                PackageInfo package = (PackageInfo)dataItem;
                if ((package.PackageType.ToUpper() == "MODULE"))
                {
                    if ((PackagesInUse.ContainsKey(package.PackageID)))
                    {
                        return "<a href=\"" + ModuleContext.EditUrl("PackageID", package.PackageID.ToString(), "UsageDetails") + "\">Yes</a>";
                    }
                    else
                    {
                        return "No";
                    }
                }
            }
            return string.Empty;
        }
        private void AddModulesToList(List<PackageInfo> packages)
        {
            Dictionary<int, PortalDesktopModuleInfo> portalModules = DesktopModuleController.GetPortalDesktopModulesByPortalID(this.ModuleContext.PortalId);
            foreach (PackageInfo modulePackage in PackageController.GetPackagesByType(Null.NullInteger, "Module"))
            {
                DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(modulePackage.PackageID);
                foreach (PortalDesktopModuleInfo portalModule in portalModules.Values)
                {
                    if (desktopModule != null && portalModule.DesktopModuleID == desktopModule.DesktopModuleID)
                    {
                        packages.Add(modulePackage);
                    }
                }
            }
        }
        private void BindGrid()
        {
            List<GamePackageInfo> packages = new List<GamePackageInfo>();
            GameController objGame = new GameController();
            packages = objGame.GetGamePackages();
            //packages = PackageController.GetPackages(Null.NullInteger);
                                
            if (packages.Count > 0)
            {
                lblNoResults.Visible = false;
                grdExtensions.Visible = true;
                grdExtensions.DataSource = packages;
                grdExtensions.DataBind();
            }
            else
            {
                grdExtensions.Visible = false;
                lblNoResults.Visible = true;
            }            
        }
        private string UpgradeIndicator(System.Version version, string packageType, string packageName, string culture)
        {
            string strURL = DotNetNuke.Services.Upgrade.Upgrade.UpgradeIndicator(version, packageType, packageName, culture, Request.IsLocal, Request.IsSecureConnection);
            if (String.IsNullOrEmpty(strURL))
            {
                strURL = DotNetNuke.Common.Globals.ApplicationPath + "/images/spacer.gif";
            }
            return strURL;
        }
        private string UpgradeRedirect(System.Version version, string packageType, string packageName, string culture)
        {
            return DotNetNuke.Services.Upgrade.Upgrade.UpgradeRedirect(version, packageType, packageName, culture);
        }
        protected string GetAboutTooltip(object dataItem)
        {
            string returnValue = string.Empty;
            try
            {
                if ((this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab))
                {
                    int portalID = Convert.ToInt32(DataBinder.Eval(dataItem, "PortalID"));
                    if ((portalID != Null.NullInteger && portalID != int.MinValue))
                    {
                        PortalInfo portal = PortalCtrl.GetPortal(portalID);
                        returnValue = string.Format(Localization.GetString("InstalledOnPortal.Tooltip", LocalResourceFile), portal.PortalName);
                    }
                    else
                    {
                        returnValue = Localization.GetString("InstalledOnHost.Tooltip", LocalResourceFile);
                    }
                }
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, ex);
            }
            return returnValue;
        }
        protected string FormatVersion(object version)
        {
            PackageInfo package = version as PackageInfo;
            string retValue = Null.NullString;
            if (package != null)
            {
                retValue = package.Version.ToString(3);
            }
            return retValue;
        }
        protected string GetPackageTypeDescription(string typeKey)
        {
            string returnValue = typeKey;
            if ((PackageTypesList.ContainsKey(typeKey)))
            {
                returnValue = PackageTypesList[typeKey].Description;
            }
            return returnValue;
        }
        protected override void OnInit(System.EventArgs e)
        {
            base.OnInit(e);
            foreach (DataGridColumn column in grdExtensions.Columns)
            {
                if (object.ReferenceEquals(column.GetType(), typeof(ImageCommandColumn)))
                {
                    ImageCommandColumn imageColumn = (ImageCommandColumn)column;
                    if (!String.IsNullOrEmpty(imageColumn.CommandName))
                    {
                        imageColumn.Text = Localization.GetString(imageColumn.CommandName, this.LocalResourceFile);
                    }
                    if (imageColumn.CommandName == "Delete")
                    {
                        string[] parameters = new string[2];
                        parameters[0] = "rtab=" + this.ModuleContext.TabId.ToString();
                        parameters[1] = "packageId=KEYFIELD";
                        string formatString = DotNetNuke.Common.Globals.NavigateURL(this.ModuleContext.TabId, "UnInstall", parameters);                        
                        formatString = formatString.Replace("KEYFIELD", "{0}");
                        imageColumn.NavigateURLFormatString = formatString;
                    }
                    if (imageColumn.CommandName == "Edit")
                    {
                        string formatString = ModuleContext.EditUrl("PackageID", "KEYFIELD", "Edit");
                        formatString = formatString.Replace("KEYFIELD", "{0}");
                        imageColumn.NavigateURLFormatString = formatString;
                    }
                }
            }
        }
        protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);

            #region Bind Handles
            grdExtensions.ItemCreated += new DataGridItemEventHandler(grdExtensions_ItemCreated);
            grdExtensions.ItemDataBound += new DataGridItemEventHandler(grdExtensions_ItemDataBound);
            #endregion

            if (!Page.IsPostBack)
            {
                Localization.LocalizeDataGrid(ref grdExtensions, LocalResourceFile);
                if (String.IsNullOrEmpty(DotNetNuke.Services.Upgrade.Upgrade.UpgradeIndicator(DotNetNukeContext.Current.Application.Version, "", "~", "", Request.IsLocal, Request.IsSecureConnection)))
                {
                    lblUpdate.Visible = false;
                    grdExtensions.Columns[8].HeaderText = "";
                }                
            }
            BindGrid();

        }

        protected override void OnPreRender(System.EventArgs e)
        {
            foreach (DataGridColumn column in grdExtensions.Columns)
            {
                if (column.HeaderText == "Type")
                {
                    column.Visible = Mode == "Skin";
                }
                if (column.FooterText == "Portal")
                {
                    column.Visible = (this.ModuleContext.IsHostMenu && (Mode == "Skin" || (Mode == "All" && (String.IsNullOrEmpty(PackageType) || PackageType == "Skin" || PackageType == "Container"))));
                }
            }
            base.OnPreRender(e);
        }
        private DataGridItem CreateGridGroupHeader(string title, string paddingTop, object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            HtmlGenericControl groupHeader = new HtmlGenericControl("div");
            groupHeader.Attributes.Add("class", "Head");
            groupHeader.InnerHtml = title;
            if ((paddingTop == string.Empty))
            {
                paddingTop = "5px";
            }
            TableCell cell = new TableCell();
            cell.Controls.Add(groupHeader);
            cell.Controls.Add(new HtmlGenericControl("hr"));
            cell.ColumnSpan = e.Item.Cells.Count;
            cell.HorizontalAlign = HorizontalAlign.Left;
            cell.Style.Add("padding-bottom", "5px");
            cell.Style.Add("padding-top", "20px");
            DataGridItem gridItem = new DataGridItem(e.Item.ItemIndex + 1, 0, ListItemType.Item);
            gridItem.Controls.Add(cell);
            return gridItem;
        }
        public string UpgradeService(System.Version version, string packageType, string packageName)
        {
            string strUpgradeService = "";
            strUpgradeService += "<a title=\"" + Localization.GetString("UpgradeMessage", this.LocalResourceFile) + "\" href=\"" + UpgradeRedirect(version, packageType, packageName, "") + "\" target=\"_new\"><img title=\"" + Localization.GetString("UpgradeMessage", this.LocalResourceFile) + "\" src=\"" + UpgradeIndicator(version, packageType, packageName, "") + "\" border=\"0\" /></a>";
            return strUpgradeService;
        }
        private IDictionary<string, PackageType> _PackageTypes = null;
        protected IDictionary<string, PackageType> PackageTypesList
        {
            get
            {
                if ((_PackageTypes == null))
                {
                    _PackageTypes = new Dictionary<string, PackageType>();
                    foreach (PackageType packageType in PackageController.GetPackageTypes())
                    {
                        _PackageTypes.Add(packageType.PackageType, packageType);
                    }
                }
                return _PackageTypes;
            }
        }
        private IDictionary<int, PackageInfo> _PackagesInUse = null;
        protected IDictionary<int, PackageInfo> PackagesInUse
        {
            get
            {
                if ((_PackagesInUse == null))
                {
                    _PackagesInUse = PackageController.GetModulePackagesInUse(PortalController.GetCurrentPortalSettings().PortalId, this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab);
                }
                return _PackagesInUse;
            }
        }
        private PortalController _PortalCtrl = null;
        protected PortalController PortalCtrl
        {
            get
            {
                if ((_PortalCtrl == null))
                {
                    _PortalCtrl = new PortalController();
                }
                return _PortalCtrl;
            }
        }
        private string _CurrentGroupKey = string.Empty;
        protected void grdExtensions_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if ((String.IsNullOrEmpty(PackageType) && Mode == "All" && e.Item != null && e.Item.DataItem != null))
            {
                if ((e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item))
                {
                    string groupTitleKey = DataBinder.Eval(e.Item.DataItem, "PackageType").ToString();
                    if ((_CurrentGroupKey != groupTitleKey))
                    {
                        DataGrid grid = (DataGrid)sender;
                        Table childTable = (Table)grid.Controls[0];
                        childTable.Rows.Add(CreateGridGroupHeader(GetPackageTypeDescription(groupTitleKey), "20px", sender, e));
                        _CurrentGroupKey = groupTitleKey;
                    }
                }
            }
        }
        protected void grdExtensions_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            DataGridItem item = e.Item;
            if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem)
            {
                HyperLink editHyperlink = item.Controls[1].Controls[0] as HyperLink;
                if (editHyperlink != null)
                {
                    PackageInfo package = (PackageInfo)item.DataItem;
                    if (this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab)
                    {
                        if (package.IsSystemPackage)
                        {
                            editHyperlink.Visible = false;
                        }
                        else
                        {
                            editHyperlink.Visible = PackageController.CanDeletePackage(package, ModuleContext.PortalSettings);
                        }
                    }
                    else
                    {
                        editHyperlink.Visible = false;
                    }
                }
                editHyperlink = item.Controls[0].Controls[0] as HyperLink;
                if (editHyperlink != null)
                {
                    editHyperlink.Visible = this.ModuleContext.IsEditable;
                }
            }
            if (String.IsNullOrEmpty(PackageType) && Mode == "All")
            {
                if (e.Item.ItemIndex == 0)
                {
                    DataGridItem row = new DataGridItem(0, 0, ListItemType.Item);
                    TableCell cell1 = new TableCell();
                    cell1.Text = "";
                    row.Cells.Add(cell1);
                    TableCell cell2 = new TableCell();
                    cell2.Text = "";
                    row.Cells.Add(cell2);
                    TableCell cell4 = new TableCell();
                    if (String.IsNullOrEmpty(Localization.GetString("AppTitle", this.LocalResourceFile)))
                    {
                        cell4.Text = DotNetNukeContext.Current.Application.Title;
                    }
                    else
                    {
                        cell4.Text = Localization.GetString("AppTitle", this.LocalResourceFile);
                    }
                    row.Cells.Add(cell4);
                    TableCell cell5 = new TableCell();
                    string appType = Localization.GetString("AppType", this.LocalResourceFile);
                    if ((appType == string.Empty))
                    {
                        appType = DotNetNukeContext.Current.Application.Type;
                    }
                    cell5.Text = appType;
                    row.Cells.Add(cell5);
                    TableCell cell6 = new TableCell();
                    cell6.Text = "";
                    row.Cells.Add(cell6);
                    TableCell cell7 = new TableCell();
                    if (String.IsNullOrEmpty(Localization.GetString("AppDescription", this.LocalResourceFile)))
                    {
                        cell7.Text = DotNetNukeContext.Current.Application.Description;
                    }
                    else
                    {
                        cell7.Text = Localization.GetString("AppDescription", this.LocalResourceFile);
                    }
                    row.Cells.Add(cell7);
                    TableCell cell8 = new TableCell();
                    cell8.Text = DotNetNukeContext.Current.Application.Version.ToString(3);
                    row.Cells.Add(cell8);
                    TableCell cell9 = new TableCell();
                    cell9.Text = UpgradeService(DotNetNukeContext.Current.Application.Version, DotNetNukeContext.Current.Application.Type, DotNetNukeContext.Current.Application.Name);
                    row.Cells.Add(cell9);
                    grdExtensions.Controls[0].Controls.AddAt(1, row);
                    grdExtensions.Controls[0].Controls.AddAt(1, CreateGridGroupHeader(appType, "", sender, e));
                }
            }
        }
        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("ModuleInstall.Action", LocalResourceFile), ModuleActionType.AddContent, "", "action_import.gif", Util.InstallURL(ModuleContext.TabId, ""), false, SecurityAccessLevel.Host, true, false);                
                return Actions;
            }
        }
    }
}